"use client";
import { ServiceTypes } from "@/api/customservice";
import { lredPacketApi, redPacketApi } from "@/api/promo";
import RedPacketModal, { RedPacketModalProps } from "@/components/Box/RedPacketModal";
import { Link } from "@/i18n";
import { useGlobalNoticeStore } from "@/stores/useGlobalNoticeStore";
import { useSocialStore } from "@/stores/useSocials";
import { getToken } from "@/utils/Cookies";
import { useRequest } from "ahooks";
import { Badge } from "antd-mobile";
import { useTranslations } from "next-intl";
import { FC, useEffect, useRef, useState } from "react";

interface Props {
    services: ServiceTypes[];
    socials: ServiceTypes[];
}
const ServiceWidget: FC<Props> = (props) => {
    const token = getToken();
    const [packets, setPackets] = useState<any[]>([]);
    const { services, socials } = props;
    const defaultService = services.find((item) => item.is_suspend === 1);

    const newServices = services.filter((item) => item.is_suspend !== 1);
    const setSocials = useSocialStore((state) => state.setSocials);
    const RedPacketModalRef = useRef<RedPacketModalProps>(null);
    useEffect(() => {
        // 数据存储，侧边栏使用
        setSocials(socials);
    }, []);

    const t = useTranslations("HomePage");
    const { unread } = useGlobalNoticeStore((state) => ({
        unread: state.unread,
    }));

    const getRedPacketInfo = async () => {
        try {
            let redPacketInfo: any;
            let actList: any = [];
            if (token) {
                redPacketInfo = await lredPacketApi();
                actList = redPacketInfo.data?.red_packets || [];
            } else {
                redPacketInfo = await redPacketApi();
                actList = redPacketInfo.data || [];
            }

            // 是否有已开始但是没领过的红包
            let isHasStartAct = actList.filter((aItem: any) => {
                return aItem.is_start && !aItem.is_receive;
            });
            console.log(`🚀🚀🚀🚀🚀-> in Service.tsx on 53`, isHasStartAct);
            setPackets(isHasStartAct);
        } catch (error) {
            console.log("redPacketInfo===>error:", error);
        }
    };
    // 红包雨轮询
    useRequest(getRedPacketInfo, {
        pollingInterval: 180000,
        pollingErrorRetryCount: 1,
        pollingWhenHidden: false,
        onSuccess: (data) => {
            console.log("data", data);
        },
    });

    return (
        <>
            {/* 红包雨icon */}
            {packets.map((item, index) => {
                return (
                    <div
                        key={index}
                        className={`absolute right-[0.12rem] z-50 flex h-[0.54rem] w-[0.54rem] cursor-pointer items-center justify-center`}
                        style={{ bottom: `${2.04 + index * 0.5}rem` }}
                    >
                        <img
                            className={"h-[0.3889rem] w-[0.3889rem]"}
                            src="/hby/red-icon.png"
                            onClick={() => {
                                RedPacketModalRef.current?.onOpen(index);
                            }}
                        />
                    </div>
                );
            })}

            {/* 红包弹窗 */}
            {/*{isShowRedPacket && (*/}
            {/*    <PopupHby*/}
            {/*        onClose={() => {*/}
            {/*            setIsShowRedPacket(false);*/}
            {/*        }}*/}
            {/*    />*/}
            {/*)}*/}
            <RedPacketModal ref={RedPacketModalRef} />

            {defaultService && (
                <Link
                    href={defaultService.url}
                    className={
                        "flex h-[0.54rem] w-[0.54rem] items-center justify-center rounded-[50%]" +
                        " absolut absolute bottom-[0.84rem] right-[0.12rem] z-50 bg-gradient-to-b from-[#ff6a01] to-primary-color"
                    }
                    target={"_blank"}
                >
                    <img
                        className={"h-[0.3889rem] w-[0.3889rem]"}
                        src={defaultService.icon_url}
                    ></img>
                </Link>
            )}

            <Link
                href={"/notification"}
                className={
                    "flex h-[0.54rem] w-[0.54rem] items-center" +
                    " absolute bottom-[1.44rem] right-[0.12rem] z-50 justify-center rounded-[50%] bg-gradient-to-b from-[#0575e6] to-[#00f260]"
                }
            >
                <Badge content={!!unread ? unread : null} style={{ "--top": "12px" }}>
                    <i className={"iconfont icon-duanxinguanli text-[0.3rem] text-[#fff]"}></i>
                </Badge>
            </Link>

            <div className={`grid grid-cols-${newServices.length >= 5 ? 5 : newServices.length}`}>
                {newServices.map((service, index) => {
                    return (
                        <Link
                            key={index}
                            href={service.url}
                            target={"_blank"}
                            className="bg-white m-[0.05rem] h-[0.3889rem] w-[0.3889rem] rounded"
                        >
                            <img
                                className={"h-[0.3889rem] w-[0.3889rem]"}
                                src={service.icon_url}
                            ></img>
                        </Link>
                    );
                })}
            </div>

            <div className={"text-[#ff6a01]"}>{t("Service")}</div>

            {/*share*/}
            <div className={"my-[0.2rem] text-[0.08rem] text-[#adadad]"}>{t("Share")}</div>

            <div className={`grid grid-cols-${socials.length >= 5 ? 5 : socials.length}`}>
                {socials.map((service, index) => {
                    return (
                        <Link
                            key={index}
                            href={service.url}
                            target={"_blank"}
                            className="bg-white m-[0.05rem] h-[0.3889rem] w-[0.3889rem] rounded"
                        >
                            <img
                                className={"h-[0.3889rem] w-[0.3889rem]"}
                                src={service.icon_url}
                            ></img>
                        </Link>
                    );
                })}
            </div>
        </>
    );
};

export default ServiceWidget;
